
<template>
  <van-nav-bar
      title="私聊"
      left-text="返回"
      left-arrow
      @click-left="onBack"
  />
  <!--  <div>
      <h1 style="font-size: 16px; text-align: center; font-weight: normal;">队伍 {{ teamId }} 的聊天室</h1>
    </div>-->
  <div class="chat-container">
    <div class="messages-container">
      <div v-for="msg in messages"  class="message">
        <div v-if="msg.fromId === userId" class="my-message">
          <div> {{ formatDate(msg.createTime) }} </div>
          {{ msg.content }}
        </div>
        <div v-else class="other-message">
          <div> {{ formatDate(msg.createTime) }} </div>
          {{ msg.username }}: {{ msg.content }}
        </div>
      </div>
    </div>

    <!-- 输入框固定在页面底部 :key="msg.id"  -->
    <div class="input-container">
      <van-field
          v-model="newMessage"
          placeholder="输入消息..."
          input-align="left"
          class="message-input"

      />
      <van-button
          icon="arrow-up"
          type="primary"
          class="send-button"
          @click="sendMessage"
      />
    </div>
  </div>
</template>


<script setup lang="ts">

import {ref, onMounted, onBeforeUnmount, nextTick, computed} from 'vue';
import { useRoute, useRouter } from 'vue-router';
import {NavBar, Field, Button, Toast} from 'vant';
import {getCurrentUser, getUserById} from "../services/user";
import myAxios from "../plugins/myAxios";
import {getCurrentUserState} from "../states/user";

const route = useRoute();
const router = useRouter();
const toId = route.params.userId;
const user= ref();  // 示例用户ID，实际应用中应从用户状态管理或路由获取
const toUser = ref();
const userId = computed(() => user.value ? user.value.id : null);
const messages = ref([]);
const newMessage = ref("");
const ws = ref(null);


//const userId = user.value.id;


onMounted(async () => {
  // 调用后端接口获取聊天记录数据
  const chatHistory = await fetchChatHistoryFromBackend();
  await getUser();
  //await getToUser();
  // 将获取到的聊天记录添加到 messages 数组中
  chatHistory.forEach(message => {
    messages.value.push(message);
  });
  // 连接 WebSocket
  connect();
});

const getUser=(async () => {
  user.value = await getCurrentUser();
  console.log(user.value);
});
/*const getToUser=(async () => {
  toUser.value = await getUserById(fromId);
  console.log(toUser.value);
});*/

// 从后端获取聊天记录数据的函数
const fetchChatHistoryFromBackend = async () => {
  // 假设这里是调用后端接口获取聊天记录数据的代码，你需要根据你的实际情况来实现
  const response = await myAxios.post('/chat/privateChat', {
    //username: username.value,
    fromId: toId,
    //timestamp: createTime.value.toISOString(),  // 使用 ISO 字符串格式的时间戳
  });
  if (response.code === 0 && response.data) {
    Toast.success('获取记录成功');
    return response.data;
  } else {
    Toast.fail('获取聊天记录失败\n'+res.description);
    return [];
  }
};

onBeforeUnmount(() => {
  if (ws.value) {
    ws.value.close();
  }
});

const connect = () => {
  let teamId = "NaN";
  let userId = user.value.id;
  console.log(userId);
  let websocketUrl;
  if (process.env.NODE_ENV === 'production') {
    // 生产环境使用线上地址
    websocketUrl = `ws://8.138.130.203:5487/api/webSocketServer/${userId}/${teamId}`;
  } else {
    // 开发环境使用本地地址
    websocketUrl = `ws://localhost:8080/api/webSocketServer/${userId}/${teamId}`;
  }
//`ws://localhost:8080/api/webSocketServer/${userId}/${teamId}`

  /*  console.log("UserID:", userId);
    console.log("TeamID:", teamId);*/
  //ws://localhost:8080/api/webSocketSever/6/6
  //ws.value = new WebSocket(`ws://localhost:8080/api/webSocketServer/${userId}/${teamId}`);
  ws.value = new WebSocket(websocketUrl);
  console.log("sb:", ws);

  ws.value.onmessage = event => {

    var a = event.data.replace(/'/g, '"');
    //console.log("isDev", isDev);
    console.log("Received message:", a);
    const message = JSON.parse(a);
    messages.value.push(message);
    nextTick(() => {
      scrollToBottom();
    });
  };

  ws.value.onopen = () => {
    console.log('WebSocket connection opened.');
  };

  ws.value.onclose = () => {
    console.log('WebSocket connection closed.');
  };

  ws.value.onerror = error => {
    console.error('WebSocket error:', error);
  };
};

const scrollToBottom = () => {
  const container = document.querySelector(".messages-container");
  if (container) {
    container.scrollTop = container.scrollHeight;
  }
}

/*const formatDate = (isoString) => {
  const date = new Date(isoString);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
};*/
const formatDate = (isoString) => {
  const date = new Date(isoString);
  // 指定时区为中国标准时间，格式化输出
  return date.toLocaleString('zh-CN', {
    timeZone: 'Asia/Shanghai',
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  });
};


const sendMessage = () => {
  //console.log(newMessage);
  if (newMessage.value.trim() !== "") {
    const message = {
      username: user.value.username,
      fromId: user.value.id,
      toId: toId,
      content: newMessage.value,
      createTime: new Date().toISOString(),  // 使用 ISO 字符串格式的时间戳
      id: Date.now()
    };
    ws.value.send(JSON.stringify(message));
    console.log(user.value.id);
    console.log(user.value.username);
    //console.log("send message:", JSON.stringify(message));
    messages.value.push(message);
    newMessage.value = "";  // Clear the input after sending
  }
};

const onBack = () => {
  router.back();
};

</script>

<style scoped>

.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh; /* 使用整个视口高度 */
}

.input-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  background-color: #fff; /* 确保背景不透明 */
  padding: 10px; /* 添加一些内边距 */
  box-shadow: 0 -2px 8px rgba(0,0,0,0.1); /* 上方添加阴影 */
}

.message-input {
  flex: 1;
}

.send-button {
  margin-left: 8px;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.message {
  margin: 10px 0;
}

.my-message {
  text-align: right;
  color: green;
}

.other-message {
  text-align: left;
  color: blue;
}

</style>